/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.cfg.sync;

import cn.easyplatform.studio.cfg.EntityLockProvider;
import cn.easyplatform.studio.dos.LockDo;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.vos.LoginUserVo;

import java.util.Iterator;
import java.util.Map;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class StdEntityLockProvider implements EntityLockProvider {

	private Map<String, LockDo> repo;

	private CommandContext cc;

	@SuppressWarnings("unchecked")
	StdEntityLockProvider(CommandContext cc) {
		this.cc = cc;
		repo = (Map<String, LockDo>) cc.getAppAttribute("ep_entity_lock");
	}

	@Override
	public String lock(String projectId, String entityId) {
		synchronized (repo) {
			LoginUserVo user = cc.getUser();
			StringBuilder sb = new StringBuilder(projectId).append(":").append(
					entityId);
			String key = sb.toString();
			sb = null;
			if (repo.containsKey(key)) {
				LockDo lock = repo.get(key);
				if (projectId.equals(lock.getProjectId())
						&& !user.getUserId().equals(lock.getUserId()))
					return lock.getUserId();
			}
			repo.put(key, new LockDo(entityId, projectId, user.getUserId()));
			return null;
		}
	}

	@Override
	public void unlock(String projectId, String entityId) {
		StringBuilder sb = new StringBuilder(projectId).append(":").append(
				entityId);
		synchronized (repo) {
			repo.remove(sb.toString());
		}
		sb = null;
	}

	@Override
	public void reset() {
		String userId = cc.getUser().getUserId();
		synchronized (repo) {
			Iterator<LockDo> itr = repo.values().iterator();
			StringBuilder sb = new StringBuilder();
			while (itr.hasNext()) {
				LockDo li = itr.next();
				if (li.getUserId().equals(userId)) {
					sb.setLength(0);
					sb.append(li.getProjectId()).append(":")
							.append(li.getEntityId());
					repo.remove(sb.toString());
				}
			}
			sb = null;
		}
	}

}
